/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sessionbean;

import entitybean.Artists;
import java.util.List;
import javax.ejb.Stateless;
import javax.management.Query;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Thien Nguyen
 */
@Stateless
@org.jboss.ejb3.annotation.RemoteBinding(jndiBinding = "ArtistsJNDI")
@org.jboss.ejb3.annotation.LocalBinding(jndiBinding = "ArtistsLocalJNDI")
public class ArtistsSessionBean implements ArtistsSessionBeanRemote, ArtistsSessionBeanLocal {

    @PersistenceContext(unitName = "J2EE_ShareMusic-ejbPU")
    private EntityManager em;

    public void persist(Object object) {
        em.persist(object);
    }

    public List loadArtist() {
        String jpql = "SELECT a FROM Artists a";
        javax.persistence.Query query = em.createQuery(jpql);
        List list = query.getResultList();
        return list;
    }

    public List getArtist(int id) {
        String jpql = "SELECT a FROM Artists a WHERE a.artistID =:id";
        javax.persistence.Query query = em.createQuery(jpql);
        query.setParameter("id", id);
        List list = query.getResultList();
        return list;
    }

    public boolean addArtist(String name) {
        String jpql = "SELECT a FROM Artists a WHERE a.artistName =:name";
        javax.persistence.Query query = em.createQuery(jpql);
        query.setParameter("name", name);
        List list = query.getResultList();
        if (list.size() == 0) {
            Artists newA = new Artists(name);
            persist(newA);
            return true;
        } else {
            return false;
        }
    }

    public boolean deleteArtist(int id) {
        String jpql = "UPDATE Songs a SET a.artists.artistID =:param WHERE a.artists.artistID =:id";
        javax.persistence.Query query = em.createQuery(jpql);
        query.setParameter("param", null);
        query.setParameter("id", id);
        int result = query.executeUpdate();
        Artists artist = em.find(Artists.class, id);
        if(artist != null) {
            em.remove(artist);
            return true;
        }
        return false;
    }


}
